package com.ruoyi.bole.controller;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.advertisement.domain.BoleBannerAd;
import com.ruoyi.advertisement.service.IBoleBannerAdService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.bole.domain.BoleContent;
import com.ruoyi.bole.service.IBoleContentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 内容信息Controller
 * 
 * @author WuJiaLe
 * @date 2025-03-22
 */
@RestController

@RequestMapping("/bole/content")
public class BoleContentController extends BaseController
{
    @Autowired
    private IBoleContentService boleContentService;

    @Autowired
    private IBoleBannerAdService boleBannerAdService;

    @Autowired
    private RedisCache redisCache;
    //查报名和流量
    @GetMapping("/registration/{contentId}")
    public AjaxResult registration(@PathVariable("contentId") Long contentId) {
        String cacheKey = "ViewCountAndRegistrationCount:" + contentId;
        // 先从 Redis 中获取缓存数据
        Object cacheData = redisCache.getCacheObject(cacheKey);
        if (cacheData != null) {
            return success(cacheData);
        }
        // 如果缓存中没有数据，从数据库中获取
        Object dataFromDb = boleContentService.getViewAndRegistrationCount(contentId);
        if (dataFromDb != null) {
            // 将从数据库中获取的数据存入 Redis，并设置过期时间
            redisCache
                    .setCacheObject(cacheKey, dataFromDb, 1, TimeUnit.HOURS);
        }
        return success(dataFromDb);
    }

    @GetMapping("/view/{contentId}")
    public AjaxResult view(@PathVariable("contentId") Long contentId) {
        try {
            // 先更新数据库中的浏览量
            boleContentService
                    .updateBoleContentViewCount(contentId);
            String cacheKey = "ViewCountAndRegistrationCount:" + contentId;
            // 从数据库中获取最新的浏览量和报名数
            Object dataFromDb = boleContentService.getViewAndRegistrationCount(contentId);
            if (dataFromDb != null) {
                // 更新 Redis 缓存
                redisCache
                        .setCacheObject(cacheKey, dataFromDb, 1, TimeUnit.HOURS);
            }
            return success();
        } catch (Exception e) {
            // 处理异常，记录日志等
            e
                    .printStackTrace();
            return error("浏览量更新失败");
        }
    }
    /**
     * 查询内容信息列表
     */
//    @PreAuthorize("@ss.hasPermi('bole:content:list')")
    @GetMapping("/list")
    public TableDataInfo list(BoleContent boleContent,Integer pageNum,Integer pageSize)
    {
        startPage();
//        System.out.println(pageNum+pageSize);
        List<BoleContent> list= boleContentService.selectBoleContentList(boleContent);
//        list= redisCache.getCacheObject( "bole:list:"+pageNum);
        return getDataTable(list);
//        if (list==null){
//            redisCache.setCacheObject("bole:list:"+pageNum, boleContentService.selectBoleContentList(boleContent));
//            list= redisCache.getCacheObject( "bole:list:"+pageNum);
//            return getDataTable(list);
//        }else{
//            redisCache.setCacheObject("bole:list:"+pageNum, boleContentService.selectBoleContentList(boleContent));
//            list= redisCache.getCacheObject( "bole:list:"+pageNum);
//            return getDataTable(list);
//        }


//        List<BoleContent> list = boleContentService.selectBoleContentList(boleContent);

//        BoleBannerAd boleBannerAd = new BoleBannerAd();
//        List list2 = boleBannerAdService.selectBoleBannerAdList(boleBannerAd);

//        return getDataTable(list);
    }

    /**
     * 导出内容信息列表
     */
    @PreAuthorize("@ss.hasPermi('bole:content:export')")
    @Log(title = "内容信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BoleContent boleContent)
    {
        List<BoleContent> list = boleContentService.selectBoleContentList(boleContent);
        ExcelUtil<BoleContent> util = new ExcelUtil<BoleContent>(BoleContent.class);
        util.exportExcel(response, list, "内容信息数据");
    }

    /**
     * 获取内容信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('bole:content:query')")
    @GetMapping(value = "/{contentId}")
    public AjaxResult getInfo(@PathVariable("contentId") Long contentId)
    {
        //补充redis
        String cacheKey = "bole:content:" + contentId;
        if (redisCache.hasKey(cacheKey)) {
            BoleContent boleContent = redisCache.getCacheObject(cacheKey);
            return success(boleContent);
        }else {
            BoleContent boleContent = boleContentService.selectBoleContentByContentId(contentId);
            redisCache.setCacheObject(cacheKey, boleContent, 1, TimeUnit.HOURS);
            return success(boleContent);
        }

    }
    //加锁
//    public AjaxResult getContent(Long contentId) {
//        String cacheKey = "bole:content:" + contentId;
//        if (redisCache.hasKey(cacheKey)) {
//            return success(redisCache.getCacheObject(cacheKey));
//        }
//
//        String lockKey = "lock:content:" + contentId;
//        String lockValue = UUID.randomUUID().toString();
//
//        // 使用SETNX + EXPIRE原子操作加锁（Redis 2.6.12+版本支持）
//        Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 30, TimeUnit.SECONDS);
//        if (!Boolean.TRUE.equals(locked)) {
//            return error("系统繁忙，请稍后再试");
//        }
//
//        try {
//            // 二次检查缓存
//            if (redisCache.hasKey(cacheKey)) {
//                return success(redisCache.getCacheObject(cacheKey));
//            }
//
//            BoleContent boleContent = boleContentService.selectBoleContentByContentId(contentId);
//            if (boleContent != null) {
//                redisCache.setCacheObject(cacheKey, boleContent, 1, TimeUnit.HOURS);
//            } else {
//                redisCache.setCacheObject(cacheKey, null, 5, TimeUnit.MINUTES);
//            }
//            return success(boleContent);
//        } finally {
//            // 释放锁（使用Lua脚本保证原子性，避免误删其他线程的锁）
//            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//            redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(lockKey), lockValue);
//        }
//    }

    /**
     * 新增内容信息
     */
    @PreAuthorize("@ss.hasPermi('bole:content:add')")
    @Log(title = "内容信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BoleContent boleContent)
    {
        //删除bole:list:下的所有缓存
        Collection<String> keys = redisCache.keys("bole:list:*");
        if (keys != null && !keys.isEmpty()) {
            // 批量删除这些键
            redisCache.deleteObject(keys);
        }
        // 获取当前登录用户的 userid
        Long userId = SecurityUtils.getUserId();
        // 将 userid 赋值给业务实体对象的相应字段
        boleContent.setUserId(userId);

        return toAjax(boleContentService.insertBoleContent(boleContent));
    }

    /**
     * 修改内容信息
     */
    @PreAuthorize("@ss.hasPermi('bole:content:edit')")
    @Log(title = "内容信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BoleContent boleContent)
    {
        //删除bole:list:下的所有缓存
        Collection<String> keys = redisCache.keys("bole:list:*");
        if (keys != null && !keys.isEmpty()) {
            // 批量删除这些键
            redisCache.deleteObject(keys);
        }
        //根据修改的id删除对应缓存
         redisCache.deleteObject(redisCache.keys("bole:content:" + boleContent.getContentId()));

        return toAjax(boleContentService.updateBoleContent(boleContent));
    }

    /**
     * 删除内容信息
     */
    @PreAuthorize("@ss.hasPermi('bole:content:remove')")
    @Log(title = "内容信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{contentIds}")
    public AjaxResult remove(@PathVariable Long[] contentIds) throws InterruptedException {
        //删除bole:content:下的所有缓存
        //删除bole:content:下的所有缓存
        Collection<String> keys = redisCache.keys("bole:content:*");
        if (keys != null && !keys.isEmpty()) {
            // 批量删除这些键
            redisCache.deleteObject(keys);
        }
        int rows = boleContentService.deleteBoleContentByContentIds(contentIds);
        // 延迟一段时间后再次删除缓存
        TimeUnit.MILLISECONDS.sleep(100); // 延迟 100 毫秒，可根据实际情况调整
        if (keys != null && !keys.isEmpty()) {
            // 批量删除这些键
            redisCache.deleteObject(keys);
        }
        return toAjax(rows);
    }
}
